<?php
!defined('QAPP') and exit('Forbidden');
include('admin_config.php');
function newtoken($input = 1)
{
    if (isset($_COOKIE['token_' . cookiehash])) {
        $token = $_COOKIE['token_' . cookiehash];
    } else {
        $token = substr(md5(time() . rand(1004, 1989)), 0, 8);
        $_COOKIE['token_' . cookiehash] = $token;
        setadmintoken($token);
    }
    if ($input == 1) {
        echo('<input type="hidden" name="qapp_token" value="' . $token . '">');
    } elseif ($input == 2) {
        echo('qapp_token=' . $token);
    } elseif ($input == 3) {
        return 'qapp_token=' . $token;
    } elseif ($input == 10) {
        return true;
    } else {
        return $token;
    }
}

function checktoken()
{
    if (isset($_POST['qapp_token'])) {
        $token = $_POST['qapp_token'];
    } elseif (isset($_GET['qapp_token'])) {
        $token = $_GET['qapp_token'];
    } else {
        adminmsg('', '非法提交,请联系管理员', 3);
    }
    if (isset($_COOKIE['token_' . cookiehash]) && $_COOKIE['token_' . cookiehash] == $token) {
        return true;
    } else {
        if (defined('loginpage')) {
            die('no token');
        }
        adminmsg('', '非法提交,请联系管理员', 3);
    }
}

function getadminname()
{
    if (isset($_COOKIE['admin_' . cookiehash]) && !empty($_COOKIE['admin_' . cookiehash])) {
        $username = trim($_COOKIE['admin_' . cookiehash]);
        if (!preg_match("/^[a-zA-Z0-9_]+$/", $username)) {
            admin_error();
        }
        return trim($username);
    } else {
        admin_error();
    }
}

function get_admin_level()
{
    $po = power('alevel');
    return $po ? $po : 0;
}

function setadminname($value, $nickname)
{
    setcookie('admin_' . cookiehash, $value, time() + 604800, "/");
    setcookie('nick_' . cookiehash, $nickname, time() + 604800, "/");
}

function setadminpsd($value)
{
    if (!empty($value)) {
        $value = md5($value . SiteHash);
    }
    setcookie('psw_' . cookiehash, $value, time() + 604800, "/");
}

function setadmintoken($value)
{
    setcookie('token_' . cookiehash, $value, time() + 604800, "/");
}

function admin_error($info = '登录信息有误,请重新登录')
{
    echo('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">');
    echo("<meta http-equiv=refresh content='0; url=login.php'>");
    exit();
}

function power($kind, $id = '', $powers = 0, $action = '')
{
    if ($powers == 0) {
        global $power;
    } else {
        $power = $powers;
    }
    if ($kind == 'alevel') {
        if (isset($power['alevel'])) {
            return $power['alevel'];
        } else {
            return 0;
        }
    }
    if ($kind == 'b') {
        if (isset($power[$kind][$id]) && $power[$kind][$id] == 1) {
            return true;
        } else {
            return false;
        }
    }
    if (isset($power['alevel']) && $power['alevel'] > 1) {
        return true;
    }
    if (!isset($power[$kind])) {
        return false;
    } elseif ($kind == 's' && !isset($power[$kind][$id][0]) && !empty($action)) {
        return false;
    } else {
        if (isset($power[$kind][$id]) && $action == '') {
            return true;
        } else {
            if (isset($power[$kind][$id][$action]) && $power[$kind][$id][$action] == 1) {
                return true;
            } else {
                return false;
            }
        }
    }
    return false;
}

function htmlinput($inputarray)
{
//    var_dump($inputarray);
    global $power;
    if ($inputarray['from']=='str'){
        $one = M()->select("ssetting as msetting", "str", "where id=?", [$inputarray['id']]);
    }else{
        $one = M()->select("msetting", "moudle", "where id=?", [$inputarray['id']]);
    }
//var_dump($one);
    $kind = $inputarray['kind'];
    $inputname = $inputarray['inputname'];
    $inputvalue = $inputarray['inputvalue'];
//    $inputvalue = str_replace( "\"", "&#34;",$inputvalue);
//    $inputvalue = str_replace( "'", "&#39;",$inputvalue);
    if (isset($inputarray['pictips'])) {
        $pictips = $inputarray['pictips'];
    } else {
        $pictips = '';
    }
    if (isset($inputarray['strarray'])) {
        $strarray = $inputarray['strarray'];
    }
    if (isset($inputarray['style'])) {
        $style = $inputarray['style'];
    } else {
        $style = '';
    }
    global $editorarray;
    if (!is_numeric($kind)) {
        return false;
    }

//    var_dump($one);
    $class="";
    $mattr="";
    if (count($one) > 0) {
        $one = $one[0];
        $obj = json_decode($one['msetting'], 1);
        $mattr = isset($obj['mattr']) ? $obj['mattr'] : "";
        $class = isset($obj['mclass']) ? $obj['mclass'] : "";
    }
//    echo $mattr,$class;
//    var_dump();

    if (strlen($style) > 5) {
        $style = ' style="' . $style . '"';
    }

    $style = $style . " " . $mattr;
    require('input/' . $kind . '.php');
    return true;
}

function filterhtml($html, $filterhtml)
{
    if (power('alevel') == 3 && ($filterhtml == 1 || $filterhtml == 2)) {
        $filterhtml = 0;
    }
    if ($filterhtml == 0) {
        return $html;
    }
    if ($filterhtml == 1) {
        return kses($html);
    }
    if ($filterhtml == 2) {
        return htmlspecialchars($html);
    }
    if ($filterhtml == 4) {
        return intval($html);
    }
    return $html;
}

function htmlinput_error($from, $id)
{
    if (isset($_GET['cid'])) {
        $cid = '&cid=' . intval($_GET['cid']);
    } else {
        $cid = '';
    }
    if (power('alevel') == 3) {
        if ($from == 'list') {
            echo('字段数据来源配置有误 <a target="_blank" href="?do=sadmin_aedit' . $cid . '&id=' . $id . '">请配置</a>');
        } elseif ($from == 'str') {
            echo('变量数据来源配置有误 <a target="_blank" href="?do=sadmin_sbasicedit' . $cid . '&id=' . $id . '">请配置</a>');
        }
    }
//    exit;
    return;
}

function inputvalue($moudle)
{
    $kind = $moudle['mkind'];
    $inputname = $moudle['mname'];
//    global $_POST;
    $othersetting = json_decode($moudle['msetting'], 1);
//    dump_pre($moudle);

    if (!isset($othersetting['filterhtml'])) {
        $filterhtml = 1;//默认过滤危险html代码
    } else {
        $filterhtml = $othersetting['filterhtml'];
    }
    if (!is_numeric($kind)) {
        return false;
    }
    switch ($kind) {
        case 2:
        case 1:
            return isset($_POST[$inputname]) ? filterhtml(htmlspecialchars_decode($_POST[$inputname]), $filterhtml) : '';
            break;
        case 4:
        case 5:
        case 3:
            return isset($_POST[$inputname]) ? filterhtml($_POST[$inputname], $filterhtml) : '';
            break;
        case 6:
            $newarray = array();
            if (isset($_POST[$inputname])) {
                unset($_POST[$inputname][0]);
                foreach ($_POST[$inputname] as $key => $val) {
                    $newarray[] = filterhtml($val, $filterhtml);
                }
            }
            return (json_encode($newarray));
            break;
        case 7:
            return isset($_POST[$inputname]) ? filterhtml($_POST[$inputname], 4) : 1;
            break;
        case 11:
        case 17:
        case 12:
        case 14:
        case 8:
            return isset($_POST[$inputname]) ? filterhtml($_POST[$inputname], 4) : 0;
            break;
        case 9:
            if ($time = strtotime($_POST[$inputname])) {
                return $time;
            }
            return 0;
            break;
        case 26:
            return isset($_POST[$inputname]) && $_POST[$inputname] == 1 ? 1 : 0;
            break;
        case 10:
            $newarray = array();
            if (isset($_POST[$inputname])) {
                unset($_POST[$inputname][0]);
                foreach ($_POST[$inputname] as $key => $val) {
                    $newarray[] = filterhtml($val, 4);
                }
            }
            return (json_encode($newarray));
            break;
        case 15:
            $newarray = array();
            if (isset($_POST[$inputname])) {
                unset($_POST[$inputname][0]);
                foreach ($_POST[$inputname] as $key => $val) {
                    $newarray[] = filterhtml($val, 4);
                }
                $newarray = array_unique($newarray);
            }
            return (json_encode($newarray));
        case 21:
            return isset($_POST[$inputname]) ? filterhtml($_POST[$inputname], 4) : 0;
        case 22:
            $newarray = array();
            if (isset($_POST[$inputname])) {
                unset($_POST[$inputname][0]);
                foreach ($_POST[$inputname] as $key => $val) {
                    $newarray[] = filterhtml($val, 4);
                }
            }
            return (json_encode($newarray));
        case 27:
            $newarray = array();
            if (isset($_POST[$inputname])) {
                foreach ($_POST[$inputname] as $key => $val) {
                    if (isset($_POST[$inputname . '-channel'][$key]) && power('s', intval($_POST[$inputname . '-channel'][$key]))) {
                        $newarray[] = array(intval($_POST[$inputname . '-channel'][$key]), intval($val));
                    }
                }
            }
            return (json_encode($newarray));
        case 19:
        case 18:
            $newarray = array();
            if (isset($_POST[$inputname])) {
                //unset($_POST[$inputname][0]);
                $_POST[$inputname] = explode(',', $_POST[$inputname]);
                foreach ($_POST[$inputname] as $key => $val) {
                    $newarray[] = filterhtml(htmlspecialchars_decode($val), $filterhtml);
                }
            }
            getHooks()->do_action('admin_tags_save', array($inputname, $newarray));
            return (json_encode($newarray));
            break;
        case 24:
            return isset($_POST['editormd' . $inputname . '-markdown-doc']) ? filterhtml($_POST['editormd' . $inputname . '-markdown-doc'], $filterhtml) : '';
            break;
        case 28:
            return isset($_POST[$inputname]) && $_POST[$inputname] > 0 ? filterhtml($_POST[$inputname], 4) : 0;
            break;
        case 29:
            $newarray = array();
            if (isset($_POST[$inputname])) {
                foreach ($_POST[$inputname] as $key => $val) {
                    if ($val > 0) {
                        $newarray[] = filterhtml($val, 4);
                    }
                }
            }
            return (json_encode($newarray));
            break;
        case 30:
            $functionname = $moudle['strarray'];
            if (function_exists($functionname)) {
                $inputvalue = $functionname('input', $inputname, '');
                return filterhtml($inputvalue, $filterhtml);
            }
            return '';
            break;
        default:
            return isset($_POST[$inputname]) ? filterhtml($_POST[$inputname], $filterhtml) : '';
    }
}

function inputkindinfo($id)
{
    global $inputkindarray;
    foreach ($inputkindarray as $val) {
        if ($id == $val['id']) {
            if (!isset($val['strfrom'])) {
                $val['strfrom'] = '';
            }
            return $val;
        }
    }
    return false;
}

function adminpagelist($recordcount, $pagesize, $curpage, $pages, $url)
{
    $totalpage = max(ceil($recordcount / $pagesize), 1);
    if ($curpage < 0 || $curpage > $totalpage) {
        $curpage = 1;
    }
    $outhtml = "";
    $pageno = $curpage;
    if ($pageno < 0 || $pageno > $totalpage) {
        $pageno = 1;
    }
    if ($pageno > 1) {
        $outhtml .= "<a href='" . str_replace('{page}', '1', $url) . "'>&lt;&lt;</a>";
    }
    if ($pages > $totalpage) {
        $startpage = 1;
        $endpage = min($startpage + $pages, $totalpage);
    } else {
        $startpage = max($totalpage - $pages, 1);
        $startpage = min($startpage, $curpage);
        $endpage = min($startpage + $pages, $totalpage);
    }
    if ($pageno > 1) {
        $outhtml .= "<a href='" . str_replace('{page}', $pageno - 1, $url) . "'>&lt;</a>";
    }
    for ($i = $startpage; $i <= $endpage; $i++) {
        if ($curpage == $i) {
            $outhtml .= "<a class=\"current\">$i</a>";
        } else {
            $outhtml .= "<a href='" . str_replace('{page}', $i, $url) . "'>$i</a>";
        }
    }
    if ($pageno < $totalpage) {
        $outhtml .= "<a href='" . str_replace('{page}', $pageno + 1, $url) . "'>&gt;</a>";
        $outhtml .= "<a href='" . str_replace('{page}', $totalpage, $url) . "'>&gt;&gt;</a>";
    }
    echo $outhtml;
}

function admin_nav($cidarray)
{
//    dump_pre($cidarray);
//    exit();
    global $cid;
    $cidarray['cname'] = isset($cidarray['cname']) ? $cidarray['cname'] : "";
    $str = '<b>' . $cidarray['cname'] . '</b>';
    $i = 0;
    while ($cidarray['fid'] <> 0) {
        $cidarray = adminchannel($cidarray['fid']);
        if ($cidarray['ckind'] == 1) {
            $str = '<b><a href="?do=str&cid=' . $cidarray['cid'] . '"/' . $cidarray['cname'] . '</a></b>' . $str;
        } elseif ($cidarray['ckind'] == 2) {
            $str = '<b><a href="?do=list&cid=' . $cidarray['cid'] . '"/' . $cidarray['cname'] . '</a></b>' . $str;
        } elseif ($cidarray['ckind'] == 3) {
            $str = '<b><a href="?do=str&cid=' . $cidarray['cid'] . '"/' . $cidarray['cname'] . '</a></b>' . $str;
        } elseif ($cidarray['ckind'] == 4) {
            $str = '<b><a href="' . $cidarray['cvalue'] . '"/' . $cidarray['cname'] . '</a></b>' . $str;
        } elseif ($cidarray['ckind'] == 5) {
            $str = '<b><a href="' . get_transit_channel($cidarray['cid'], 2) . '"/' . $cidarray['cname'] . '</a></b>' . $str;
        }
        $i++;
        if ($i > 66) {
            return $str;
        }
    }
    return $str;

}

function admin_nav_list($cid, $son = 0)
{
    global $channels, $power;
    $fid = 0;
    $count = 0;
    foreach ($channels as $value) {
        if ($cid == $value['cid']) {
            $fid = $value['fid'];
        }
        if ($value['fid'] == $cid && power('s', $value['cid'], $power)) {
            if ($value['ifshowadmin'] == 1) {
                $count++;
                $zzssqqw = 1;
                if ($son == $value['cid']) {
                    $style = ' class="on"';
                } else {
                    $style = '';
                }
                if ($value['ckind'] == 1) {
                    echo('<a' . $style . ' href="?do=str&cid=' . $value['cid'] . '">' . $value['cname'] . '</a>');
                } elseif ($value['ckind'] == 2) {
                    echo('<a' . $style . ' href="?do=list&cid=' . $value['cid'] . '">' . $value['cname'] . '</a>');
                } elseif ($value['ckind'] == 3) {
                    echo('<a' . $style . ' href="?do=str&cid=' . $value['cid'] . '">' . $value['cname'] . '</a>');
                } elseif ($value['ckind'] == 4) {
                    if ($value['newwindow'] == 1) {
                        echo('<a' . $style . ' href="' . $value['cvalue'] . '" target="_blank">' . $value['cname'] . '</a>');
                    } else {
                        echo('<a' . $style . ' href="' . $value['cvalue'] . '">' . $value['cname'] . '</a>');
                    }
                } elseif ($value['ckind'] == 5) {
                    echo('<a' . $style . ' href="' . get_transit_channel($value['cid'], 2) . '">' . $value['cname'] . '</a>');
                }
            }
        }
    }
    if (!isset($zzssqqw) && $fid > 0) {
        admin_nav_list($fid, $cid);
    }
    if ($count == 1) {
        echo('<script type="text/javascript">$(function(){$("#urHere a.on").hide();});</script>');
    }
}

function admin_nav_list_array($cid, $son = 0)
{
    global $channels, $power;
    $fid = 0;
    $count = 0;
    $navlinks = array();
    foreach ($channels as $value) {
        if ($cid == $value['cid']) {
            $fid = $value['fid'];
        }
        if ($value['fid'] == $cid && power('s', $value['cid'], $power)) {
            if ($value['ifshowadmin'] == 1) {
                $count++;
                $zzssqqw = 1;

                if ($value['ckind'] == 1 || $value['ckind'] == 3) {
                    $navlinks[] = array('url' => "?do=str&cid={$value['cid']}", 'title' => $value['cname']);
                } elseif ($value['ckind'] == 2) {
                    $navlinks[] = array('url' => "?do=list&cid={$value['cid']}", 'title' => $value['cname']);
                } elseif ($value['ckind'] == 4) {
                    if ($value['newwindow'] == 1) {
                        $navlinks[] = array('url' => $value['cvalue'], 'title' => $value['cname'], 'target' => "_blank");
                    } else {
                        $navlinks[] = array('url' => $value['cvalue'], 'title' => $value['cname']);
                    }
                } elseif ($value['ckind'] == 5) {
                    $navlinks[] = array('url' => "?do=list&cid=" . get_transit_channel($value['cid'], 2), 'title' => $value['cname']);
                }
            }
        }
    }
    if (!isset($zzssqqw) && $fid > 0) {
        array_merge($navlinks, admin_nav_list_array($fid, $cid));
    }

    return $navlinks;
}

function adminmsg($url, $msg, $s = 3, $pagename = '列表页')
{
    if (isset($_GET['nohtml']) && $_GET['nohtml']) {
        echo('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">');
        echo($msg);
        if (!empty($url)) {
            resp_goto_url($url, $s);
        }
        exit;
    }
    echo('<script>$(function(){$(document).keydown(function(event){var ctrlc = event.which;var key=ctrlc-48;if (key>0 && key<10){keygourl=$(\'.AdminMsg\').find(\'a\').eq(key-1).attr(\'href\');if (keygourl.length>3){window.location.href=keygourl;}}});});</script>');
    if ($url == '') {
        admin_page_start("信息提示");
        echo('<h3>信息提示</h3><div class="AdminMsg"><h2>' . $msg . '</h2><dl><dt>请<a href="javascript:history.go(-1);">返回</a>。</dt><dd><a href="javascript:history.go(-1);">返回上一页</a></dd></dl></div>');
        admin_page_end();
    } else {
        $jsurl = str_replace("\\", "\\\\", $url);
        admin_page_start("信息提示");
        echo('<h3>信息提示</h3><div class="AdminMsg"><h2>' . $msg . '</h2><dl><dt>如果您不做出选择，将在 ' . $s . ' 秒后跳转到' . $pagename . ' (按Enter键直接跳转)。</dt><dd><a href="javascript:history.go(-1);">返回上一页</a></dd></dl></div><script type="text/javascript">$(document).keydown(function(event){var ctrlc = event.which; if(ctrlc == 13 || ctrlc ==32){window.location.href = "' . $jsurl . '";}});</script>');
        resp_goto_url($url, $s);
        admin_page_end();
    }
    exit;
}

function clink($count)
{
    $str = '';
    for ($i = 0; $i < $count - 1; $i++) {
        $str .= '──';
    }
    return $str;
}

function adminchannelscache()
{
    global $channels;
    if (!is_array($channels)) {
        M()->query("SELECT * FROM " . tableex('channel') . " order by corder asc");
        $channels = M()->fetchall();
    }
    return $channels;
}

function getleftlist($cdaddy = 0, $times = 0)
{
    global $channels;
    global $power, $cid;
    $times++;
    $mynav = array();
    foreach ($channels as $value) {
        if ($value['fid'] == $cdaddy && $times < 5) {
            if ($value['ifshowleft'] == 1 && $value['ifshowadmin'] == 1 && power('s', $value['cid'], $power)) {
                if ($value['ckind'] == 1) {
                    $mynav[] = array('url' => '?do=str&cid=' . $value['cid'], 'title' => $value['cname'], 'cid' => $value['cid'], 'fid' => $value['fid'], 'blank' => '');
                } elseif ($value['ckind'] == 2) {
                    $mynav[] = array('url' => '?do=list&cid=' . $value['cid'], 'title' => $value['cname'], 'cid' => $value['cid'], 'fid' => $value['fid'], 'blank' => '');
                } elseif ($value['ckind'] == 3) {
                    $mynav[] = array('url' => '?do=str&cid=' . $value['cid'], 'title' => $value['cname'], 'cid' => $value['cid'], 'fid' => $value['fid'], 'blank' => '');
                } elseif ($value['ckind'] == 4) {
                    $value['cvalue']=str_replace('(cid)', $value['cid'], $value['cvalue']);
                    if ($value['newwindow'] == 1) {
                        $mynav[] = array('url' => $value['cvalue'], 'title' => $value['cname'], 'cid' => $value['cid'], 'fid' => $value['fid'], 'blank' => 'target="_blank"');
                    } else {
                        $mynav[] = array('url' => $value['cvalue'], 'title' => $value['cname'], 'cid' => $value['cid'], 'fid' => $value['fid'], 'blank' => '');
                    }
                } elseif ($value['ckind'] == 5) {
                    $mynav[] = array('url' => get_transit_channel($value['cid'], 2), 'title' => $value['cname'], 'cid' => $value['cid'], 'fid' => $value['fid'], 'blank' => '');
                }
            }
        }
    }
    getHooks()->do_action('admin_left_loop_before');
    if (count($mynav) > 0) {
        foreach ($mynav as $thisnav) {
            if ($thisnav['fid'] == 0) {
                echo("<ul class='' rel='{$thisnav['cid']}'><hr>");
            }
            $style = '';
            if ($times >= 2) {
                $style .= 'text-indent:' . (($times - 1) * 10) . 'px;';
            }
            if ($cid == $thisnav['cid']) {
                $ifon = "active";
            } else {
                $ifon = '';
            }

            echo("<a href='{$thisnav['url']}' {$thisnav['blank']}><li class='{$ifon}'  style='{$style}' rel='{$thisnav['cid']}'>{$thisnav['title']}");
            getHooks()->do_action('admin_left_loop');
            echo('</li></a>' . "\r\n");
            getleftlist($thisnav['cid'], $times);
            if ($thisnav['fid'] == 0) {
                echo('</ul>');
            }
        }
    }
    return count($mynav);
}

function adminchannel($cid)
{
    global $channels;
    if (!isset($channels) || count($channels) == 0) {
        return false;
    }
    foreach ($channels as $key => $val) {
        if ($val['cid'] == $cid) {
            return $val;
        }
    }
    return false;
}

function channel_select($selectid = 0, $fid = 0, $i = 0, $returnstr = 1, $topname = '--顶级栏目--')
{
    $i = $i + 1;
    global $channels;
    $returnarray = array();
    if ($fid == 0) {
        if ($returnstr) {
            echo('<option value="0">' . $topname . '</option>');
        }
    }
    if (is_array($channels)) {
        foreach ($channels as $channel) {
            if ($channel['fid'] == $fid) {
                if ($returnstr) {
                    if ($selectid == $channel['cid']) {
                        echo('<option value="' . $channel['cid'] . '" selected>├' . clink($i) . $channel['cname'] . '</option>');
                    } else {
                        echo('<option value="' . $channel['cid'] . '">├' . clink($i) . $channel['cname'] . '</option>');
                    }
                } else {
                    $returnarray[] = array('cname' => $channel['cname'], 'ext' => '├' . clink($i * 2), 'cid' => $channel['cid'], 'fid' => $channel['fid'], 'ifshowadmin' => $channel['ifshowadmin'], 'ckind' => $channel['ckind'], 'corder' => $channel['corder'], 'cvalue' => $channel['cvalue'], 'ifshow' => $channel['ifshow'], 'csetting' => $channel['csetting']);
                }
                $nextchannel = channel_select($selectid, $channel['cid'], $i, $returnstr);
                if ($nextchannel && count($nextchannel) > 0) {
                    foreach ($nextchannel as $val) {
                        $returnarray[] = $val;
                    }
                }
            }
        }
    }
    if (!$returnstr) {
        return $returnarray;
    }
}

function treeselect($category, $inputvalue, $thisdaddy = 0, $i = 0)
{
    $i = $i + 1;
//    dump_pre($category);
    if (isset($category[0])) {
        foreach ($category[0] as $key => $val) {
            if ($key <> 'id' && $key <> 'fid' && !is_numeric($key)) {
                $mname = $key;
            }
        }
    }
    foreach ($category as $value) {

        if ($value['fid'] == $thisdaddy) {
            if ($value['id'] == $inputvalue) {
                echo('<option value="' . $value['id'] . '" selected>├' . clink($i) . $value[$mname] . '</option>');
            } else {
                echo('<option value="' . $value['id'] . '">├' . clink($i) . $value[$mname] . '</option>');
            }
            treeselect($category, $inputvalue, $value['id'], $i);
        }
    }
}

function getlistcolumn($cid, $setting = array())
{
    $columnssql = array();
    $columnssql[] = 'id';
    $columnssql[] = 'cid';
    $columnssql[] = 'posttime';
    $columnssql[] = 'adminuid';
    $columns = M()->all("SELECT cid,ifshowtemp,hide,mname,ifshow FROM " . tableex('moudle') . " where  cid='$cid' and ifcreated='1' order by morder asc");
    foreach ($columns as $key => $val) {
        if ($val['hide'] <> 1 && $val['ifshow'] == 1) {
            if (!in_array($val['mname'], $columnssql)) {
                $columnssql[] = $val['mname'];
            }

        }
        if (strlen($val['ifshowtemp']) > 2) {
            $pattern = "/[{|\[|(](.*)[}|\]|)]/U";
            preg_match_all($pattern, $val['ifshowtemp'], $match);
            if (isset($match[1])) {
                foreach ($match[1] as $matchval) {
                    if (!in_array($matchval, $columnssql)) {
                        $ifin = 0;
                        foreach ($columns as $columnsval) {
                            if ($columnsval['mname'] == $matchval) {
                                $ifin = 1;
                            }
                        }
                        if ($ifin == 1) {
                            $columnssql[] = $matchval;
                        }
                    }
                }
            }
        }

    }
    if (in_array('title', $columnssql) && isset($setting['channel_articleurl'])) {
        $pattern = "/[{|\[|(](.*)[}|\]|)]/U";
        preg_match_all($pattern, $setting['channel_articleurl'], $match);
        if (isset($match[1])) {
            foreach ($match[1] as $matchval) {
                if (!in_array($matchval, $columnssql)) {
                    $ifin = 0;
                    foreach ($columns as $columnsval) {
                        if ($columnsval['mname'] == $matchval) {
                            $ifin = 1;
                        }
                    }
                    if ($ifin == 1) {
                        $columnssql[] = $matchval;
                    }
                }
            }
        }
    }
    return implode(',', $columnssql);
}

function getlistsearchcolumn($cid)
{
    $columnsarray = array();
    $columnsarray[] = 'id';
    $columns = M()->all("SELECT mname,msetting FROM " . tableex('moudle') . " where  cid='$cid' and ifcreated='1' and hide<>1 order by morder asc");
    foreach ($columns as $key => $val) {
        $msetting = json_decode($val['msetting'], 1);
        if (isset($msetting['adminsearch'])) {
            $columnsarray[] = $val['mname'];
        }
    }
    return $columnsarray;
}

function admintablecheck($tablename)
{
    if (empty($tablename)) {
        return true;
    }
    return preg_match("/^[A-Za-z0-9_]+$/", $tablename);
}

function adminchannelcache($cid)
{
    $channel = uuu_getchannelcache($cid);
    if (!$channel) {
        return false;
    }
    if (!isset($channel['csetting']['articletable']) || empty($channel['csetting']['articletable'])) {
        return false;
    }
    if (isset($channel['csetting']['temppage_order']) && strlen($channel['csetting']['temppage_order']) > 3) {
        $channel['csetting']['temppage_order'] = 'order by ' . $channel['csetting']['temppage_order'];
    } else {
        $channel['csetting']['temppage_order'] = 'order by id desc';
    }
    return $channel;
}

function channeltable($cid, $articletable)
{
    $articletable = tableex($articletable);
    if (!M()->creatTable($articletable)) {
        echo M()->errorMessage();
        exit();
    }

    $articletablelist = M()->getTableDLL($articletable);
    if (!$articletablelist) {
        echo M()->errorMessage();
        exit();
    }

    $cols = array('posttime' => QAppDB::COL_TYPE_BIGINT, 'cid' => QAppDB::COL_TYPE_INT, 'adminuid' => QAppDB::COL_TYPE_INT);
    foreach ($cols as $colname => $coltype) {
        if (stripos($articletablelist['sql'], '[' . $colname . ']') > 0 || stripos($articletablelist['sql'], ' ' . $colname . ' ') > 0) {
            //存在了
        }else{
            M()->addColumn($articletable, $colname, $coltype);
        }
    }

    $links = M()->all("SELECT * FROM " . tableex('moudle') . " where cid='$cid' and hide<>'1' order by morder asc");
    $countmoudle = 0;
    foreach ($links as $link) {
        if (stripos($articletablelist['sql'], '[' . $link['mname'] . ']') > 0 || stripos($articletablelist['sql'], ' ' . $link['mname'] . ' ') > 0) {

        } else {
            $countmoudle++;
            $mkind = $link['mkind'];
            $mname = $link['mname'];
            $val = inputkindinfo($mkind);
            if ($val) {
                if (isset($val['kind']) && $val['kind'] == 'int') {
                    M()->addColumn($articletable, $mname, QAppDB::COL_TYPE_INT);
                } elseif (isset($val['kind']) && $val['kind'] == 'varchar') {
                    M()->addColumn($articletable, $mname, QAppDB::COL_TYPE_VARCHAR255);
                } elseif (isset($val['kind']) && $val['kind'] == 'text') {
                    M()->addColumn($articletable, $mname, QAppDB::COL_TYPE_TEXT);
                } elseif (isset($val['kind'])) {
                    M()->addColumn($articletable, $mname, $val['kind']);
                } else {
                    M()->addColumn($articletable, $mname, QAppDB::COL_TYPE_VARCHAR255);
                }
            }
        }
    }
    if ($countmoudle > 0) {
        return true;
    } else {
        return 'no';
    }
}

function postroutercheck($str, $ifurl = 0)
{
    $str = str_replace("；", ';', $str);
    $str = str_replace("（", '(', $str);
    $str = str_replace("）", ')', $str);
    $str = str_replace("。", '.', $str);
    if ($ifurl == 1) {
        $strs = explode(';', $str);
        foreach ($strs as $key => $val) {
            if (!empty($val)) {
                $strs[$key] = '/' . ltrim($val, '/');
            } else {
                unset($strs[$key]);
            }
        }
        $str = implode(';', $strs);
    }
    $str = str_replace("'", '', $str);
    $str = str_replace('"', '', $str);
    $str = str_replace("\\", '/', $str);
    return trim($str);
}

function channelrouter()
{
    $allurl = array();
//    $allurl[] = array('uri' => '/', 'res' => 'm/index', 'domain' => SystemDomain, 'cache' => IndexCache, 'cid' => 0);
    $diyurl = M()->one("SELECT * FROM " . tableex('str') . " where strname='diyurl' and inputkind=0 limit 1;");
    if ($diyurl) {
        $diyurl = json_decode($diyurl['strvalue'], 1);
        if ($diyurl) {
            foreach ($diyurl as $val) {
                !isset($val['method']) && $val['method'] = 'all';
                !isset($val['domain']) && $val['domain'] = '';
                $allurl[] = array('method' => $val['method'], 'uri' => $val['uri'], 'res' => $val['res'], 'domain' => $val['domain'], 'cache' => $val['cache'], 'cid' => 0);
            }
        }
    }
    $channels = M()->all("SELECT * FROM " . tableex('channel') . " order by cid asc");
    foreach ($channels as $key => $val) {
        $csetting = json_decode($val['csetting'], 1);
        if ($val['ifshow'] > 0) {
            if (!isset($csetting['channel_domain'])) {
                $csetting['channel_domain'] = '';
            }
            if ($val['ckind'] == 1) {
                if (isset($csetting['channel_url']) && isset($csetting['template']) && isset($csetting['channel_urlcache']) && strlen($csetting['channel_url']) > 0 && !empty($csetting['template'])) {
                    $csetting['channel_url'] = str_replace("(cid)", $val['cid'], $csetting['channel_url']);
                    $csetting['template'] = str_replace("(cid)", $val['cid'], $csetting['template']);
                    $allurl[] = array('uri' => $csetting['channel_url'], 'res' => $csetting['template'], 'cache' => $csetting['channel_urlcache'], 'cid' => $val['cid'], 'domain' => $csetting['channel_domain']);
                }
            } elseif ($val['ckind'] == 2) {
                if (isset($csetting['channel_url']) && isset($csetting['template']) && isset($csetting['channel_urlcache']) && substr($csetting['channel_url'], 0, 1) !== '!' && strlen($csetting['channel_url']) > 0 && !empty($csetting['template'])) {
                    $csetting['channel_url'] = str_replace("(cid)", $val['cid'], $csetting['channel_url']);
                    $csetting['template'] = str_replace("(cid)", $val['cid'], $csetting['template']);
                    $allurl[] = array('uri' => $csetting['channel_url'], 'res' => $csetting['template'], 'cache' => $csetting['channel_urlcache'], 'cid' => $val['cid'], 'domain' => $csetting['channel_domain']);
                }
                if (isset($csetting['channel_pageurl']) && isset($csetting['templatelist']) && isset($csetting['channel_pageurlcache']) && strlen($csetting['channel_pageurl']) > 0 && !empty($csetting['templatelist'])) {
                    $csetting['channel_pageurl'] = str_replace("(cid)", $val['cid'], $csetting['channel_pageurl']);
                    $csetting['templatelist'] = str_replace("(cid)", $val['cid'], $csetting['templatelist']);
                    $allurl[] = array('uri' => $csetting['channel_pageurl'], 'res' => $csetting['templatelist'], 'cache' => $csetting['channel_urlcache'], 'cid' => $val['cid'], 'domain' => $csetting['channel_domain']);
                }
                if (isset($csetting['channel_articleurl']) && isset($csetting['templatearticle']) && isset($csetting['channel_articleurlcache']) && strlen($csetting['channel_articleurl']) > 0 && !empty($csetting['templatearticle'])) {
                    $csetting['channel_articleurl'] = str_replace("(cid)", $val['cid'], $csetting['channel_articleurl']);
                    $csetting['templatearticle'] = str_replace("(cid)", $val['cid'], $csetting['templatearticle']);
                    $allurl[] = array('uri' => $csetting['channel_articleurl'], 'res' => $csetting['templatearticle'], 'cache' => $csetting['channel_articleurlcache'], 'cid' => $val['cid'], 'domain' => $csetting['channel_domain']);
                }
            }
            if (isset($csetting['otherpage'])) {
                $otherpagearray = json_decode($csetting['otherpage'], 1);
                foreach ($otherpagearray as $otherpage) {
                    if (isset($otherpage['uri']) && isset($otherpage['res']) && !empty($otherpage['res']) && isset($otherpage['cache'])) {
                        $otherpage['uri'] = str_replace("(cid)", $val['cid'], $otherpage['uri']);
                        $otherpage['res'] = str_replace("(cid)", $val['cid'], $otherpage['res']);
                        $allurl[] = array('uri' => $otherpage['uri'], 'res' => $otherpage['res'], 'cache' => $otherpage['cache'], 'cid' => $val['cid'], 'domain' => $csetting['channel_domain']);
                    }
                }
            }
        }
    }
    $allurl = json_encode($allurl);
    $routerquery = M()->one("SELECT strvalue FROM " . tableex('str') . " where strname='router' and inputkind=0 limit 1;");
    if (!$routerquery) {
        $query = M()->query("INSERT INTO `" . tableex('str') . "` (`strname`,`strcid`,`strorder`,`inputkind`,`strvalue`,`ifadmin`) VALUES ('router','0','0','0',?,'1');", array($allurl));
    } else {
        $query = M()->query("UPDATE " . tableex('str') . " SET strvalue=? WHERE strname='router' and inputkind=0;", array($allurl));
        cache_site_del('router', 'str');
    }
    if ($query) {
        return true;
    } else {
        return false;
    }
}

function get_transit_channel($cid, $kind = 1)
{
    $cid = intval($cid);
    global $channels, $power;
    if ($kind == 1) {
        foreach ($channels as $key => $val) {
            if ($val['fid'] == $cid && $val['ifshow'] == 1) {
                if ($val['ckind'] == 5) {
                    return get_transit_channel($val['cid']);
                } else {
                    return uuu_getchannelurl($val['cid']);
                }
            }
        }

    }
    if ($kind == 2) {
        foreach ($channels as $key => $val) {
            if ($val['fid'] == $cid && $val['ifshowadmin'] == 1 && power('s', $val['cid'], $power)) {
                if ($val['ckind'] == 5) {
                    return get_transit_channel($val['cid'], 2);
                } elseif ($val['ckind'] == 1 || $val['ckind'] == 3) {
                    return "?do=str&cid=" . $val['cid'];
                } elseif ($val['ckind'] == 2) {
                    return "?do=list&cid=" . $val['cid'];
                } elseif ($val['ckind'] == 4) {
                    return $val['cvalue'];
                }
            }
        }
    }
    return '#';
}

function transit_channel_cache()
{
    global $channels;
    foreach ($channels as $key => $val) {
        if ($val['ckind'] == 5) {
            $value = get_transit_channel($val['cid']);
            $query = M()->query("UPDATE " . tableex('channel') . " SET cvalue=? WHERE cid=?", array($value, $val['cid']));
            if (!$query) {
                return false;
            }
        }
    }
    return true;
}

/**
 * 加载原始的管理页面
 * @param $dir
 * @param $file
 * @return bool|string
 */
function load_admin_parent($dir, $file)
{
    if (!preg_match("/^[a-z\d]{1,25}$/i", $dir)) {
        return false;
    }
    if (!preg_match("/^[a-z\d]{1,25}$/i", $file)) {
        return false;
    }

    $admin_file = AdminDir . $dir . '/' . $file . '.php';
    if (!is_file($admin_file)) {
        return false;
    }
    return (AdminDir . $dir . '/' . $file . '.php');
}

/**
 * 加载管理页面组建
 * @param $dir
 * @param $file
 * @return bool|string
 */
function load_admin_file($dir, $file)
{
    if (!preg_match("/^[a-z\d]{1,25}$/i", $dir)) {
        return false;
    }
    if (!preg_match("/^[a-z\d]{1,25}$/i", $file)) {
        return false;
    }


    $app_admin_file = AppDir . 'admin/' . $dir . '/' . $file . '.php';
    if (is_file($app_admin_file)) {
        return (AppDir . 'admin/' . $dir . '/' . $file . '.php');
    } else {
        $admin_file = AdminDir . $dir . '/' . $file . '.php';
        if (!is_file($admin_file)) {
            return false;
        }
        return (AdminDir . $dir . '/' . $file . '.php');
    }
}

function admin_page_start($pageTitle, $right_links = array())
{
    global $cid, $thisdo;
    $links = "";
    foreach ($right_links as $right_link) {
        $links .= "<a class='btn btn-link btn-xs' href='{$right_link['url']}'>{$right_link['title']}</a>";
    }

    $cid_label = "";
    if (power('alevel') >= 2 && uuu_cfg("开发模式") && $thisdo[0] != 'sadmin') {
        $cid_label = "<span>[cid:<code>$cid</code>]</span>";
    }
    $cid_edit = '';

    if (get_admin_level() == 3 && $thisdo[0] != 'sadmin' && ($thisdo[1] == 'index' || $thisdo[1] == '')) {
        if ($thisdo[0] == 'str') {
            $cid_edit = "<a href='?do=sadmin_sbasic&cid={$cid}'><em>变量配置</em></a> ";
            if ($cid > 0) {
                $cid_edit .= "<a href='?do=sadmin_cedit&cid={$cid}'><em>栏目配置</em></a> ";
            }
        } else if ($cid > 0) {
            $cid_edit = "<a href='?do=sadmin_cedit&cid={$cid}'><em>栏目配置</em></a> ";
            $cid_edit .= "<a href='?do=sadmin_sbasic&cid={$cid}'><em>变量配置</em></a> ";
            $cid_edit .= "<a href='?do=sadmin_aindex&cid={$cid}'><em>字段配置</em></a> ";
        }
    }

    $outline = "";
    $inline = "";
    if (count($right_links) < 6) {
        $inline = "<div class='navbar-right' style='margin: -2px 0 0 0;'>{$links}</div>";
    } else {
        $outline = "<br><nav class='breadcrumb'>子栏目：$links</nav>";
    }

    $here = "<div id='UMain'><nav id='urHere' class='breadcrumb'>{$cid_label} 后台管理 / <b>{$pageTitle}</b>{$inline} {$cid_edit}</nav>";


    echo $here . $outline . '<div id="mainBox">';
}

function admin_page_end()
{
    echo "</div></div>";
}

function file_download_base64($filename, $filecontent)
{
    $filecontent = base64_encode(json_encode($filecontent));
    Header("Content-type:application/octet-stream");
    Header("Accept-Ranges:bytes");
    header("Content-Disposition:attachment;filename=" . $filename . ".txt");
    header("Expires:0");
    header("Cache-Control:must-revalidate,post-check=0,pre-check=0");
    header("Pragma:public");
    echo($filecontent);
    die();
}